import React, { useState, useEffect } from 'react';
import { Modal, Button, Progress, DatePicker, message, Typography } from 'antd';
import dayjs from 'dayjs';
import request from '@/utils/request';

const { Text, Link } = Typography;

export type ReleaseType = 1 | 2 | 3; // 1 立即发布 2 定时发布 3 发布列表

interface FileItem {
  data_type: string;
  product_id: string;
}

interface DataReleaseModalProps {
  open: boolean;
  onCancel: () => void;
  releaseType: ReleaseType;
  files: FileItem[];
  onSuccess?: () => void;
}

const DataReleaseModal: React.FC<DataReleaseModalProps> = ({
  open,
  onCancel,
  releaseType,
  files,
  onSuccess
}) => {
  const [scheduledTime, setScheduledTime] = useState<string>(dayjs().format('YYYY-MM-DD HH:mm:ss'));
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [progressInfo, setProgressInfo] = useState<any>(null);
  const [releaseTaskId, setReleaseTaskId] = useState<number | null>(null);
  const [errorMsg, setErrorMsg] = useState<string>('');
  const [step, setStep] = useState<'init' | 'progress'>('init');
  const [intervalId, setIntervalId] = useState<any>(null);

  useEffect(() => {
    if (!open) {
      setProgress(0);
      setProgressInfo(null);
      setReleaseTaskId(null);
      setErrorMsg('');
      setStep('init');
      if (intervalId) clearInterval(intervalId);
    }
    // eslint-disable-next-line
  }, [open]);

  // 轮询进度
  useEffect(() => {
    if (releaseTaskId && step === 'progress') {
      const id = setInterval(async () => {
        try {
          const res = await request.get('/Management/DataReleaseSchedule', {
            params: { release_task_id: releaseTaskId }
          });
          if (res.status === 200 && res.data.data) {
            const { total_release_count, release_success_count, release_surplus_count } = res.data.data;
            setProgressInfo(res.data.data);
            setProgress(Math.round((release_success_count / total_release_count) * 100));
            if (release_success_count + release_surplus_count >= total_release_count) {
              clearInterval(id);
              setIntervalId(null);
              setTimeout(() => {
                onSuccess && onSuccess();
                onCancel();
              }, 1000);
            }
          }
        } catch (e) {
          setErrorMsg('推送中断，原因：网络中断');
          clearInterval(id);
          setIntervalId(null);
        }
      }, 1000);
      setIntervalId(id);
      return () => clearInterval(id);
    }
    // eslint-disable-next-line
  }, [releaseTaskId, step]);

  // 提交发布
  const handleRelease = async () => {
    setLoading(true);
    setErrorMsg('');
    try {
      const res = await request.post('/Management/DataRelease', {
        release_type: releaseType,
        scheduled_release_time: releaseType === 2 ? scheduledTime : undefined,
        files
      });
      if (res.status === 200 && res.data.data) {
        if (releaseType === 3) {
          message.success('已添加至发布列表');
          onSuccess && onSuccess();
          onCancel();
          return;
        }
        setReleaseTaskId(res.data.data.release_task_id);
        setProgressInfo({
          total_release_count: res.data.data.release_file_count,
          release_success_count: 0,
          release_surplus_count: res.data.data.release_file_count
        });
        setStep('progress');
        if (releaseType === 1) {
          setProgress(0);
        }
        message.success('发布任务已提交');
      } else {
        message.error(res.data.msg || '发布失败');
      }
    } catch (e: any) {
      setErrorMsg(e?.message || '发布失败');
      message.error(e?.message || '发布失败');
    } finally {
      setLoading(false);
    }
  };

  // 弹窗内容
  let content = null;
  if (releaseType === 1 && step === 'progress') {
    // 立即发布进度
    content = (
      <div style={{ textAlign: 'center' }}>
        <div style={{ marginBottom: 8 }}>
          <Text>
            共{progressInfo?.total_release_count || 0}条数据，已推送{progressInfo?.release_success_count || 0}条，剩余{progressInfo?.release_surplus_count || 0}条
          </Text>
        </div>
        {errorMsg && <div style={{ color: 'red', marginBottom: 8 }}>{errorMsg}</div>}
        <div style={{ margin: '16px 0' }}>
          <Progress percent={progress} status={errorMsg ? 'exception' : 'active'} />
        </div>
        <Button onClick={onCancel}>关闭</Button>
      </div>
    );
  } else if (releaseType === 2) {
    // 定时发布，显示时间选择器
    content = (
      <div style={{ textAlign: 'center' }}>
        <div style={{ marginBottom: 8 }}>
          <Text>
            共{files.length}条数据。
          </Text>
        </div>
        <div style={{ margin: '16px 0' }}>
          <span>推送时间：</span>
          <DatePicker
            showTime
            value={dayjs(scheduledTime)}
            onChange={val => setScheduledTime(val ? val.format('YYYY-MM-DD HH:mm:ss') : '')}
            format="YYYY-MM-DD HH:mm:ss"
            style={{ width: 200 }}
          />
        </div>
        <div style={{ marginTop: 16 }}>
          <Button type="primary" loading={loading} onClick={handleRelease} style={{ marginRight: 8 }}>
            确定
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </div>
      </div>
    );
  } else if (releaseType === 3) {
    // 添加至发布列表，不显示时间选择器
    content = (
      <div style={{ textAlign: 'center' }}>
        <div style={{ marginBottom: 8 }}>
          <Text>
            共{files.length}条数据。
          </Text>
        </div>
        <div style={{ marginTop: 16 }}>
          <Button type="primary" loading={loading} onClick={handleRelease} style={{ marginRight: 8 }}>
            确定
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </div>
      </div>
    );
  } else {
    // 立即发布初始弹窗（未进入进度）
    content = (
      <div style={{ textAlign: 'center' }}>
        <div style={{ marginBottom: 8 }}>
          <Text>
            共{files.length}条数据。
          </Text>
        </div>
        <div style={{ marginTop: 16 }}>
          <Button type="primary" loading={loading} onClick={handleRelease} style={{ marginRight: 8 }}>
            发布
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </div>
      </div>
    );
  }

  return (
    <Modal
      open={open}
      title={releaseType === 1 ? (step === 'progress' ? '立即发布' : '立即发布') : releaseType === 2 ? '定时发布' : releaseType === 3 ? '添加至发布列表' : '发布列表'}
      footer={null}
      onCancel={onCancel}
      destroyOnHidden
      maskClosable={false}
    >
      {content}
    </Modal>
  );
};

export default DataReleaseModal; 